<?php

namespace App\Http\Controllers\Api;

use Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\Services\DrugService;
use App\Models\ZZMed\ZHospMember;

class DrugController extends Controller {

    public $drugService;
    public static $validation;

    public function __construct(DrugService $drugService) {
        $this->drugService = $drugService;
    }

    /**
     * 用药选择列表 
     * mode ：1垂体疾病用药 2降糖用药 3降压药物 4其它用药
     */
    public function getDrugs(Request $request) {
        $data = $request->all();
        $validator = Validator::make($data,
                        [
                            'user_id' => 'required',
                            'mode'  => 'required'
                        ],
                        [
                            'user_id.required' => '患者Id必须',
                            'mode.required' => '用药mode必须'
                        ]
        );

        if ($validator->fails()) {
            return $this->error(42200, $validator->errors()->all()[0]);
        }
        //1垂体疾病用药 2降糖用药 3降压药物 4其它用药
        $userId = $data['user_id'];
        $ret = $this->drugService->getDrugs($data['mode']);
        $usedDrugs = $this->getUsedDrugs($userId,$data['mode']);
        $data = [
            "used_drugs" => $usedDrugs,
            "list" => $ret
        ];
        return $this->success($data);
    }

    /**
     * 用户使用的用药列表 考虑到其他用药 用别名全匹配
     */
    public function getUsedDrugs($userId = 0,$mode) {
        $data = [
            "drug_ids" => [],
            "drugs" => [],
        ];
        $drugs = $this->drugService->getUsedDrugs($userId,$mode);

        foreach ($drugs as $drug) {
            $drugId = $drug->drug_id;
            $typeId = $drug->type_id;
            //202,203,204,205为其他用药 
            if (in_array($drugId, [202,203,204,205])) {
                $data["drug_ids"][] = $drug->drug_alias;
            } else {
                $data["drug_ids"][] = $drugId;
            }
            $data["drugs"][$typeId][] = $drugId;
        }
        return $data;
    }

    /**
     * 用药检查
     */
    public function drugCheck(Request $request) {
        //用药 新增 编辑 不可以与现有的用药重复  重新开始 该用药现在状态为停药
        //用药剂量 不合理
        //用药互斥 不合理 
        $data = $request->all();
        $validate = Validator::make($data, [
                    'user_id' => 'required',
                    'drug_id' => 'required',
                    'type_id' => 'required', //用药类别
                    'drug_alias' => 'required_if:drug_id,202,203,204,205',
                    'drug_dose' => 'required', // 总剂量
//                    'week_dose' => 'required_if:drug_id,185,198', // 百达扬  度易达 必须
                    'drug_times' => 'required_if:type_id,30,31,32,33,34,35,36,37,38', //胰岛素必填次数
                    'unit' => 'required',
                    'is_used' => 'required',
                    'start_date' => 'required|date_format:Y-m-d',
                    'end_date' => 'required_if:is_used,0|date_format:Y-m-d|after:start_date',
                    'op_id' => 'required', //操作医生
                    'mode' => 'required'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, $validate->errors()->toJson());
        }

        $userId = $data["user_id"];
        $drugId = $data["drug_id"];

        //如果用药正在使用 直接返回
        $usedDrugs = $this->getUsedDrugs($userId,$data['mode']);
        //对于其他用药
        if (in_array($drugId, [202,203,204,205])) {
            //使用别名校验
            $authDrugId = $data["drug_alias"];
        } else {
            $authDrugId = $drugId;
        }
        if (in_array($authDrugId, $usedDrugs["drug_ids"])) {
            return $this->error(42200, "用药正在使用，不能重复添加");
        }

        return $this->success($data);
    }

    public function serializeUsageDosageOther($usageDose, $type = 1) {
        if (!$usageDose) {
            return "";
        }
        $content = "";
        if ($type == 1) {
            $content = serialize($usageDose);
        } else {
            $content = unserialize($usageDose);
        }

        return $content;
    }

    /**
     * 用药添加 (纯新增 重新开始用药 补填用药)
     */
    public function drugAdd(Request $request) {
        $data = $request->all();
        $validate = Validator::make($data, [
                    'user_id' => 'required',
                    'drug_id' => 'required',
                    'type_id' => 'required', //用药类别
                    'drug_alias' => 'required_if:drug_id,202,203,204,205',
                    'drug_dose' => 'required',
                    //'week_dose' => 'required_if:drug_id,185,198', // 百达扬  度易达 必须
                    'drug_times' => 'required_if:type_id,30,31,32,33,34,35,36,37,38', //胰岛素必填次数
                    'unit' => 'required',
                    'is_used' => 'required',
                    'start_date' => 'required|date_format:Y-m-d',
                    'end_date' => 'required_if:is_used,0|date_format:Y-m-d|after:start_date',
                    'op_id' => 'required', //操作医生
        ]);
        if ($validate->fails()) {
            return $this->error(42200, $validate->errors()->toJson());
        }
        //胰岛素 次数必填 [31,32,33,34,35,36,54,55]
        //每周计量 week_dose [185,198]
        //总剂量  drug_dose ![185,198]
        //部分字段获取 及 初始化
        $data["drug_alias"] = in_array($data["drug_id"], [202,203,204,205]) && isset($data["drug_alias"]) ? $data["drug_alias"] : "";
        $data["drug_dose"] = isset($data["drug_dose"]) ? $data["drug_dose"] : 0;
        //$data["week_dose"] = in_array($data["drug_id"], [185, 198]) && isset($data["week_dose"]) ? $data["week_dose"] : 0;
        $data["drug_times"] = in_array($data["type_id"], [30,31,32,33,34,35,36,37,38]) && isset($data["drug_times"]) ? $data["drug_times"] : 0;

        if (in_array($data["drug_id"], [202,203,204,205]) && !$data["drug_alias"]) {
            return $this->error(42200, "请填写用药别名");
        } else if (in_array($data["drug_id"], [202,203,204,205]) && $data["drug_alias"] == "其他") {
            return $this->error(42200, "药物别名不能为其他，请修改为正确的药物别名");
        } else if ($data["drug_dose"] == 0) {
            return $this->error(42200, "请填写剂量");
        }else if (in_array($data["type_id"], [30,31,32,33,34,35,36,37,38]) && $data["drug_times"] == 0) {
            return $this->error(42200, "请填写胰岛素次数");
        }
        $data["end_date"] = $data["is_used"] == 0 && isset($data["end_date"]) ? $data["end_date"] : "0001-01-01";
        $data["adjust_date"] = "0001-01-01";
        $data["usage_dosage_morning"] = $data["usage_dosage_morning"] ?? 0;
        $data["usage_dosage_noon"] = $data["usage_dosage_noon"] ?? 0;
        $data["usage_dosage_night"] = $data["usage_dosage_night"] ?? 0;
        $data["usage_dosage_bedtime"] = $data["usage_dosage_bedtime"] ?? 0;
        $usageDosageOther = $data["usage_dosage_other"] ?? "";
        $data["usage_dosage_other"] = $this->serializeUsageDosageOther($usageDosageOther, 1);
        $data["remark"] = $data["remark"] ?? "";
        $data["is_new"] = 1;
        //
        $data["week_dose"] = 0;
        /**
         * 判断该药是否停药 如果停药 场景3  如果没有 场景1/2
         */
        $drugInfo = $this->drugService->getDrugDetailByUserId($data["user_id"], $data["drug_id"], $data["drug_alias"]);

        $retId = 0;
        if ($drugInfo && isset($drugInfo->is_used)) {
            if ($drugInfo->is_used == 1) {
                return $this->error(42200, "该用药正在使用!");
            } else {
                //场景3  重新开始用药  
                if ($data["start_date"] <= $drugInfo->end_date) {
                    return $this->error(42200, "该用药上次停药时间为" . $drugInfo->end_date . ",请重新选择用药开始时间！");
                } else {
                    //重新启用用药 
                    //不能更新用药 以及 别名 其他都可以更新
                    $updateData = [];
                    foreach ($data as $key => $val) {
                        if ($key == "drug_id" || $key == "drug_alias") {
                            continue;
                        } else {
                            $updateData[$key] = $val;
                        }
                    }
                    if ($data["is_used"] == 1) {
                        //更新最新的用药 且 插入用药记录 
                        $updateData["is_used"] = 1;
                        $updateData["end_date"] = "0001-01-01"; //强制
                        $retId = $this->drugService->updateGetId("z_pituitary_manage_drugs", $updateData, $drugInfo->id);
                        //插入记录
                        $itemData = $data;
                        $itemData["pituitary_drugs_id"] = $retId;
                        $itemData["relation_records_id"] = $drugInfo->relation_records_id;
                        $itemData["is_used"] = 1;
                        $itemData["end_date"] = "0001-01-01";
                        $itemData["adjust_date"] = "0001-01-01";
                        $itemData["drug_type"] = 4; //重新启用
                        $recordId = $this->drugService->insertGetId("z_pituitary_manage_drugs_records", $itemData);
                        //更新依赖关系
                        $this->drugService->updateGetId("z_pituitary_manage_drugs", ["relation_records_id" => $recordId], $retId);
                    } else if ($data["is_used"] == 0) {
                        //更新最新的用药 且 插入用药记录
                        $updateData["is_used"] = 0;
                        $updateData["end_date"] = $data["end_date"];
                        $retId = $this->drugService->updateGetId("z_pituitary_manage_drugs", $updateData, $drugInfo->id);
                        //插入到记录表 z_pituitary_manage_drugs_records 
                        $itemData = $data;
                        $itemData["pituitary_drugs_id"] = $retId;
                        //插入到记录表 即开始时间
                        $itemData["relation_records_id"] = $drugInfo->relation_records_id;
                        $itemData["is_used"] = 1;
                        $itemData["end_date"] = "0001-01-01";
                        $itemData["adjust_date"] = "0001-01-01";
                        $itemData["drug_type"] = 4; //重新启用
                        $recordInsertId = $this->drugService->insertGetId("z_pituitary_manage_drugs_records", $itemData);
                        //插入到记录表 即结束时间
                        $itemData["relation_records_id"] = $recordInsertId;
                        $itemData["is_used"] = 0;
                        $itemData["start_date"] = $data["start_date"];
                        $itemData["adjust_date"] = "0001-01-01";
                        $itemData["end_date"] = $data["end_date"];
                        $itemData["drug_type"] = 3; //停药
                        $recordId = $this->drugService->insertGetId("z_pituitary_manage_drugs_records", $itemData);
                        //更新关系
                        $this->drugService->updateGetId("z_pituitary_manage_drugs", ["relation_records_id" => $recordId], $retId);
                    }
                }
            }
        } else {
            $itemData = $data;
            if ($itemData["is_used"] == 1) {
                //场景1 纯新增 (正在使用)
                //插入到主表 z_pituitary_manage_drugs
                $retId = $this->drugService->insertGetId("z_pituitary_manage_drugs", $itemData);
                //插入到记录表 z_pituitary_manage_drugs_records
                $itemData["pituitary_drugs_id"] = $retId;
                $itemData["relation_records_id"] = 0;
                $itemData["drug_type"] = 1; //新增
                $recordId = $this->drugService->insertGetId("z_pituitary_manage_drugs_records", $itemData);
                //更新关系
                $this->drugService->updateGetId("z_pituitary_manage_drugs", ["relation_records_id" => $recordId], $retId);
            } else if ($itemData["is_used"] == 0) {
                //场景2 如果是停药 需要插入一条新增 插入一条停药 2条记录
                //插入到主表 z_pituitary_manage_drugs
                $retId = $this->drugService->insertGetId("z_pituitary_manage_drugs", $itemData);
                //插入到记录表 z_pituitary_manage_drugs_records 
                $itemData["pituitary_drugs_id"] = $retId;
                //插入到记录表 即开始时间
                $itemData["relation_records_id"] = 0;
                $itemData["is_used"] = 1;
                $itemData["adjust_date"] = "0001-01-01";
                $itemData["end_date"] = "0001-01-01";
                $itemData["drug_type"] = 1; //新增
                $recordInsertId = $this->drugService->insertGetId("z_pituitary_manage_drugs_records", $itemData);
                //插入到记录表 即结束时间
                $itemData["relation_records_id"] = $recordInsertId;
                $itemData["is_used"] = 0;
                $itemData["start_date"] = $data["start_date"];
                $itemData["adjust_date"] = "0001-01-01";
                $itemData["end_date"] = $data["end_date"];
                $itemData["drug_type"] = 3; //停药
                $recordId = $this->drugService->insertGetId("z_pituitary_manage_drugs_records", $itemData);
                //更新关系
                $this->drugService->updateGetId("z_pituitary_manage_drugs", ["relation_records_id" => $recordId], $retId);
            }
        }

        return $this->success(["id" => $retId]);
    }

    /**
     * 用药编辑 外部编辑
     */
    public function drugEdit(Request $request) {
        $data = $request->all();
        $validate = Validator::make($data, [
                    'records' => 'required',
                    'op_id' => 'required', //操作医生
                    'user_id' => 'required'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, $validate->errors()->toJson());
        }

        //获取这些用药的提交时间 
        $dataTime = [];
        $dateLastTime = [];
        foreach ($data["records"] as $item) {
            $lastRelation = $item["relation_records_id"];
            $nextRelation = $item["id"];
            $dateLastTime[$nextRelation] = $lastRelation;
            if ($item["drug_type"] == 1 || $item["drug_type"] == 4) {
                $dataTime[$lastRelation]["date"] = $item['start_date'];
                $dataTime[$lastRelation]["next_id"] = $nextRelation;
            } else if ($item["drug_type"] == 2) {
                $dataTime[$lastRelation]["date"] = $item['adjust_date'];
                $dataTime[$lastRelation]["next_id"] = $nextRelation;
            } else if ($item["drug_type"] == 3) {
                $dataTime[$lastRelation]["date"] = $item['end_date'];
                $dataTime[$lastRelation]["next_id"] = $nextRelation;
            }
            $dataTime[$lastRelation]["last_id"] = isset($dateLastTime[$lastRelation]) ? $dateLastTime[$lastRelation] : 0;
        }


        try {
            DB::beginTransaction();
            $pituitaryDrugsId = 0;
            foreach ($data["records"] as $item) {
                $dataRelation = [];
                $item["op_id"] = $data["op_id"];
                $line = $item["line"];
                $nextline = $line + 1;
                //获取外部用药的ID
                if ($pituitaryDrugsId == 0) {
                    $pituitaryDrugsId = $item["pituitary_drugs_id"];
                }
                //如果是新药 这里做一下限制 避免改错用药 
                $lastRelation = $item["relation_records_id"];
                //新增用药
                if ($item["drug_type"] == 1 || $item["drug_type"] == 4) {
                    $item["adjust_date"] = "0001-01-01";
                    $item["end_date"] = "0001-01-01";
                    $dataRelation["start_date"] = $item['start_date'];
                    //判断时间  
                    $validEditDate = $this->validRelationDate($dataRelation["start_date"], $dataTime, $lastRelation);
                    //不生效
                    if ($validEditDate["last_date"] == 0 || $validEditDate["next_date"] == 0) {
                        DB::rollBack();
                    }
                    //返回行错误
                    if ($validEditDate["last_date"] == 0) {
                        return $this->error(42200, "第" . $line . "行用药记录开始时间应该大于上一行记录时间");
                    } else if ($validEditDate["next_date"] == 0) {
                        return $this->error(42200, "第" . $line . "行用药记录开始时间应该小于下一行记录时间");
                    }
                } else if ($item["drug_type"] == 2) {
                    //调整时 用药开始时间不更新
                    if (isset($item["start_date"])) {
                        unset($item["start_date"]);
                    }
                    $item["end_date"] = "0001-01-01";
                    $dataRelation["adjust_date"] = $item['adjust_date'];

                    $validEditDate = $this->validRelationDate($dataRelation["adjust_date"], $dataTime, $lastRelation);
                    //不生效
                    if ($validEditDate["last_date"] == 0 || $validEditDate["next_date"] == 0) {
                        DB::rollBack();
                    }
                    //返回行错误
                    if ($validEditDate["last_date"] == 0) {
                        return $this->error(42200, "第" . $line . "行用药记录调整时间应该大于上一行记录时间");
                    } else if ($validEditDate["next_date"] == 0) {
                        return $this->error(42200, "第" . $line . "行用药记录调整时间应该小于下一行记录时间");
                    }
                } else if ($item["drug_type"] == 3) {
                    //用药停止时 不更新用药开始时间和调整时间
                    if (isset($item["start_date"])) {
                        unset($item["start_date"]);
                    }
                    $item["adjust_date"] = '0001-01-01';
                    $dataRelation["end_date"] = $item['end_date'];

                    $validEditDate = $this->validRelationDate($dataRelation["end_date"], $dataTime, $lastRelation);
                    //不生效
                    if ($validEditDate["last_date"] == 0 || $validEditDate["next_date"] == 0) {
                        DB::rollBack();
                    }
                    //返回行错误
                    if ($validEditDate["last_date"] == 0) {
                        return $this->error(42200, "第" . $line . "行用药记录结束时间应该大于上一行记录时间");
                    } else if ($validEditDate["next_date"] == 0) {
                        return $this->error(42200, "第" . $line . "行用药记录结束时间应该小于下一行记录时间");
                    }
                }
                //编辑
                $usageDosageOther = $item["usage_dosage_other"] ?? "";
                $item["usage_dosage_other"] = $this->serializeUsageDosageOther($usageDosageOther, 1);
                $this->drugService->updateGetId("z_pituitary_manage_drugs_records", $item, $item["id"]);
                if ($dataRelation) {
                    $this->drugService->updateGetId("z_pituitary_manage_drugs", $dataRelation, $item["id"], "relation_records_id");
                    $dataRelation = [];
                }
            }

            //重新计算用药z_pituitary_manage_drugs应该有的状态
            $this->updateIsUsedDrugs($pituitaryDrugsId);
        } catch (Exception $e) {
            Log::error('Database Exception:', [$e->getMessage(), $e->getTrace()]);
            DB::rollBack();
        }
        DB::commit();
        return $this->success([]);
    }

    /**
     * 
     * @param type $currentDate 当前时间
     * @param type $dataTime 上下关系
     * @param type $index 当前索引
     */
    public function validRelationDate($currentDate, $dataTime, $index) {
        //不存在 不判断
        if (!isset($dataTime[$index])) {
            return [
                "last_date" => 0,
                "next_date" => 0
            ];
        }

        $lastId = $dataTime[$index]["last_id"];
        $nextId = $dataTime[$index]["next_id"];
        $date = $dataTime[$index]["date"];

        $lastDate = 0;
        $nextDate = 0;

        if ($lastId == 0) {
            //不用判断上行关系时间
            $lastDate = 1;
        } else {
            if ($currentDate > $dataTime[$lastId]["date"]) {
                $lastDate = 1;
            } else {
                $lastDate = 0;
            }
        }


        if (isset($dataTime[$nextId]) && $dataTime[$nextId]) {
            if ($currentDate < $dataTime[$nextId]["date"]) {
                $nextDate = 1;
            } else {
                $nextDate = 0;
            }
        } else {
            //不判断下行关系时间
            $nextDate = 1;
        }

        return [
            "last_date" => $lastDate,
            "next_date" => $nextDate
        ];
    }

    /**
     * 旧版用药 取ID最大的一条作为本条更新的状态
     * 新版用药 忽略
     */
    public function updateIsUsedDrugs($newDrugId) {
        //取用药记录的最新一次记录 不含当条
        $lastDrugInfo = $this->drugService->getLastDrugRecord(0, $newDrugId);
        if (!$lastDrugInfo) {
            //同步删除主表记录
            $data2["is_deleted"] = 1;
            $data2["remark"] = "被医生附带删除，doc_id:" . $data["op_id"];
            $this->drugService->updateGetId("z_pituitary_manage_drugs", $data2, $newDrugId);
        } else {
            //记录存在 ，以次新条记录更新记录 主要体现在
            $data2["drug_dose"] = $lastDrugInfo->drug_dose;
            $data2["week_dose"] = $lastDrugInfo->week_dose;
            $data2["drug_times"] = $lastDrugInfo->drug_times;
            $data2["unit"] = $lastDrugInfo->unit;
            $data2["is_used"] = $lastDrugInfo->is_used;
            $data2["start_date"] = $lastDrugInfo->start_date;
            $data2["end_date"] = $lastDrugInfo->end_date;
            $data2["adjust_date"] = $lastDrugInfo->adjust_date;
            $data2["usage_dosage_morning"] = $lastDrugInfo->usage_dosage_morning;
            $data2["usage_dosage_noon"] = $lastDrugInfo->usage_dosage_noon;
            $data2["usage_dosage_night"] = $lastDrugInfo->usage_dosage_night;
            $data2["usage_dosage_bedtime"] = $lastDrugInfo->usage_dosage_bedtime;
            $data2["usage_dosage_other"] = $lastDrugInfo->usage_dosage_other;
            $data2["remark"] = $lastDrugInfo->remark;
            //关联关系修正
            $data2["relation_records_id"] = $lastDrugInfo->id;
            $this->drugService->updateGetId("z_pituitary_manage_drugs", $data2, $newDrugId);
        }
        return true;
    }

    /**
     * 用药调整  
     * id  记录ID  
     */
    public function drugAdjust($id, Request $request) {
        $data = $request->all();
        $validate = Validator::make($data, [
                    'user_id' => 'required',
                    'drug_id' => 'required',
                    'type_id' => 'required', //用药类别
                    'drug_alias' => 'required_if:drug_id,202,203,204,205',
                    'drug_times' => 'required_if:type_id,30,31,32,33,34,35,36,37,38', //胰岛素必填次数
                    'drug_dose' => 'required',
                    'unit' => 'required',
                    'adjust_date' => 'required|date_format:Y-m-d',
                    'op_id' => 'required', //操作医生
        ]);
        if ($validate->fails()) {
            return $this->error(42200, $validate->errors()->toJson());
        }
        //胰岛素 次数必填 [31,32,33,34,35,36,54,55]
        //每周计量 week_dose [185,198]
        //总剂量  drug_dose ![185,198]
        //部分字段获取 及 初始化 
        $data["drug_dose"] = isset($data["drug_dose"]) ? $data["drug_dose"] : 0;
        $data["week_dose"] = 0;
        $data["drug_times"] = in_array($data["type_id"], [30,31,32,33,34,35,36,37,38]) && isset($data["drug_times"]) ? $data["drug_times"] : 0;
                

        if ($data["drug_dose"] == 0) {
            return $this->error(42200, "请填写剂量");
        }else if (in_array($data["type_id"], [30,31,32,33,34,35,36,37,38]) && $data["drug_times"] == 0) {
            return $this->error(42200, "请填写胰岛素次数");
        }

        // 当前用药状态 存在且正在使用 调整以后 用药依然是正在使用状态 开始时间 不变 结束时间 空  调整时间 
        $info = $this->drugService->getRecordDetailById($id);
        if (!$info || !isset($info->is_used)) {
            return $this->error(42200, "数据异常，找不到该用药记录");
        } else if ($info->is_used == 0) {
            return $this->error(42200, "数据异常，该用药状态为停药不支持调整，请先重新启用");
        }

        if ($data["adjust_date"] <= $info->start_date) {
            return $this->error(42200, "该用药当前开始时间为" . $info->start_date . ",请重新选择用药调整时间！");
        } else if ($info->adjust_date > "0001-01-01" && $data["adjust_date"] <= $info->adjust_date) {
            return $this->error(42200, "该用药上次调整时间为" . $info->adjust_date . ",请重新选择用药调整时间！");
        }

        //调整用药 
        $data["usage_dosage_morning"] = $data["usage_dosage_morning"] ?? 0;
        $data["usage_dosage_noon"] = $data["usage_dosage_noon"] ?? 0;
        $data["usage_dosage_night"] = $data["usage_dosage_night"] ?? 0;
        $data["usage_dosage_bedtime"] = $data["usage_dosage_bedtime"] ?? 0;
        //$data["usage_dosage_other"] = $data["usage_dosage_other"] ?? "";
        $usageDosageOther = $data["usage_dosage_other"] ?? "";
        $data["usage_dosage_other"] = $this->serializeUsageDosageOther($usageDosageOther, 1);
        $data["remark"] = $data["remark"] ?? "";
        $data["is_new"] = 1;
        //更新最新的用药 且 插入用药记录 
        $updateData = [];
        foreach ($data as $key => $val) {
            #这里过滤掉额外参数 避免前端传参影响数据
            if (in_array($key, ["user_id", "drug_id", "drug_alias", "start_date", "end_date"])) {
                continue;
            } else {
                $updateData[$key] = $val;
            }
        }
        $updateData["is_used"] = 1;
        $updateData["end_date"] = "0001-01-01"; //强制
        $retId = $this->drugService->updateGetId("z_pituitary_manage_drugs", $updateData, $id);
        //插入记录
        $itemData = $data;
        $itemData["pituitary_drugs_id"] = $retId;
        $itemData["relation_records_id"] = $info->relation_records_id;
        $itemData["is_used"] = 1;
        $itemData["start_date"] = $info->start_date;
        $itemData["end_date"] = "0001-01-01";
        $itemData["drug_type"] = 2; //重新启用
        $recordId = $this->drugService->insertGetId("z_pituitary_manage_drugs_records", $itemData);
        //更新关系
        $this->drugService->updateGetId("z_pituitary_manage_drugs", ["relation_records_id" => $recordId], $retId);
        return $this->success(["id" => $retId]);
    }

    /**
     * 用药停药
     */
    public function drugStop($id, Request $request) {
        // 当前用药状态 存在且正在使用 停药以后 用药停药状态 开始时间 不变 调整时间 空  停药时间
        $data = $request->all();
        $validate = Validator::make($data, [
                    'end_date' => 'required|date_format:Y-m-d',
                    'op_id' => 'required', //操作医生
        ]);
        if ($validate->fails()) {
            return $this->error(42200, $validate->errors()->toJson());
        }
        // 当前用药状态 存在且正在使用 调整以后 用药依然是正在使用状态 开始时间 不变 结束时间 空  调整时间 
        $info = $this->drugService->getRecordDetailById($id);
        if (!$info || !isset($info->is_used)) {
            return $this->error(42200, "数据异常，找不到该用药记录");
        } else if ($info->is_used == 0) {
            return $this->error(42200, "数据异常，该用药已经是停药状态");
        }

        if ($data["end_date"] <= $info->start_date) {
            return $this->error(42200, "该用药当前开始时间为" . $info->start_date . ",请重新选择用药停药时间！");
        } else if ($info->adjust_date > "0001-01-01" && $data["end_date"] <= $info->adjust_date) {
            return $this->error(42200, "该用药上次调整时间为" . $info->adjust_date . ",请重新选择用药停药时间！");
        }
        $data["remark"] = $data["remark"] ?? "";
        $updateData = [];
        //更新最新的用药 且 插入用药记录  
        $updateData["is_used"] = 0;
        $updateData["remark"] = $data["remark"];
        $updateData["end_date"] = $data["end_date"];
        $retId = $this->drugService->updateGetId("z_pituitary_manage_drugs", $updateData, $id);
        //插入记录 初始化
        $data["drug_dose"] = $info->drug_dose;
        $data["week_dose"] = $info->week_dose;
        $data["drug_times"] = $info->drug_times;
        $data["unit"] = $info->unit;
        $data["usage_dosage_morning"] = $info->usage_dosage_morning;
        $data["usage_dosage_noon"] = $info->usage_dosage_noon;
        $data["usage_dosage_night"] = $info->usage_dosage_night;
        $data["usage_dosage_bedtime"] = $info->usage_dosage_bedtime;
        $data["usage_dosage_other"] = $info->usage_dosage_other;
        $data["start_date"] = $info->start_date;
        $data["adjust_date"] = $info->adjust_date;
        $data["is_new"] = 1;
        $itemData = $data;
        $itemData["pituitary_drugs_id"] = $id;
        $itemData["relation_records_id"] = $info->relation_records_id;
        $itemData["is_used"] = 0;
        $itemData["drug_type"] = 3; //停药 
        $recordId = $this->drugService->insertGetId("z_pituitary_manage_drugs_records", $itemData);
        //更新关系
        $this->drugService->updateGetId("z_pituitary_manage_drugs", ["relation_records_id" => $recordId], $retId);
        return $this->success(["id" => $retId]);
    }

    /**
     * 用药删除 外部列表删除
     */
    public function drugDel($id, Request $request) {
        $data = $request->all();
        $validate = Validator::make($data, [
                    'op_id' => 'required',
                    'user_id' => 'required'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, $validate->errors()->toJson());
        }
        $updateData["is_deleted"] = 1;
        $updateData["remark"] = "被医生删除，doc_id:" . $data["op_id"];
        $this->drugService->updateGetId("z_pituitary_manage_drugs", $updateData, $id);

        $data1["is_deleted"] = 1;
        $data1["op_id"] = $data["op_id"];
        $this->drugService->updateGetId("z_pituitary_manage_drugs_records", $data1, $id, "pituitary_drugs_id");
        return $this->success([]);
    }

    /**
     * 用药内部列表删除 
     */
    public function drugDelRecord($id, Request $request) {
        $data = $request->all();
        $validate = Validator::make($data, [
                    'op_id' => 'required',
                    'user_id' => 'required'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, $validate->errors()->toJson());
        }


        $recordInfo = $this->drugService->getDrugRecord($id);
        if (!$recordInfo) {
            return $this->error(42200, "数据异常，找不到该条用药记录");
        }

        $newDrugId = $recordInfo->pituitary_drugs_id; //主表ID 
        //查看列表用药是否依赖本条 是否是最后一条 
        $info = $this->drugService->getDrugRelationId($id);
        if (!$info) {
            return $this->error(42200, "数据异常，该用药不是最后一条");
        }

        $data1["is_deleted"] = 1;
        $data1["op_id"] = $data["op_id"];
        $this->drugService->updateGetId("z_pituitary_manage_drugs_records", $data1, $id);

        //取用药记录的最新一次记录 不含当条
        $lastDrugInfo = $this->drugService->getLastDrugRecord($id, $newDrugId);
        if (!$lastDrugInfo) {
            //同步删除主表记录
            $data2["is_deleted"] = 1;
            $data2["remark"] = "被医生附带删除，doc_id:" . $data["op_id"];
            $this->drugService->updateGetId("z_pituitary_manage_drugs", $data2, $newDrugId);
        } else {
            //记录存在 ，以次新条记录更新记录 主要体现在
            $data2["drug_dose"] = $lastDrugInfo->drug_dose;
            $data2["week_dose"] = $lastDrugInfo->week_dose;
            $data2["drug_times"] = $lastDrugInfo->drug_times;
            $data2["unit"] = $lastDrugInfo->unit;
            $data2["is_used"] = $lastDrugInfo->is_used;
            $data2["start_date"] = $lastDrugInfo->start_date;
            $data2["end_date"] = $lastDrugInfo->end_date;
            $data2["adjust_date"] = $lastDrugInfo->adjust_date;
            $data2["usage_dosage_morning"] = $lastDrugInfo->usage_dosage_morning;
            $data2["usage_dosage_noon"] = $lastDrugInfo->usage_dosage_noon;
            $data2["usage_dosage_night"] = $lastDrugInfo->usage_dosage_night;
            $data2["usage_dosage_bedtime"] = $lastDrugInfo->usage_dosage_bedtime;
            $data2["usage_dosage_other"] = $lastDrugInfo->usage_dosage_other;
            $data2["remark"] = $lastDrugInfo->remark;
            //关联关系修正
            $data2["relation_records_id"] = $lastDrugInfo->id;
            $this->drugService->updateGetId("z_pituitary_manage_drugs", $data2, $newDrugId);
        }
        return $this->success([]);
    }
    
    /**
     * 用药点击查看列表
     */
    public function getDrugRecordsList($id,Request $request) {

        //支持分页显示 //支持新旧分开显示 
        // //保留分页 后面可能要改
        $data = $request->all();
        $pageNo = isset($data["page_no"]) && $data["page_no"] ? $data["page_no"] - 1 : 0;
        $pageSize = isset($data["page_size"]) && $data["page_size"] ? $data["page_size"] : 1000;
        $total = $this->drugService->getDrugRecordsListTotal($id);
 
        if ($total == 0) {
            return $this->error(42200, "数据异常，该用药记录不存在");
        }
        $list = $this->drugService->getDrugRecordsList($id, $pageNo, $pageSize);
        $retList = [];
        foreach ($list as $item) { 
                if ($item["drug_type"] == 1 || $item["drug_type"] == 4) {
                    $item["end_date"] = "0001-01-01";
                    $item["adjust_date"] = "0001-01-01";
                } else if ($item["drug_type"] == 2) {
                    $item["start_date"] = "0001-01-01";
                    $item["end_date"] = "0001-01-01";
                } else if ($item["drug_type"] == 3) {
                    $item["start_date"] = "0001-01-01";
                    $item["adjust_date"] = "0001-01-01";
                }
                
                $item['doc_name'] = ZHospMember::getDocName($item['op_id']);

                $usageDosageOther = $item["usage_dosage_other"] ?? "";
                $item["usage_dosage_other"] = $this->serializeUsageDosageOther($usageDosageOther, 2);

                $retList[] = $item;
            
        } 
        return $this->success(["total" => $total, "list" => $retList]);
    }

    
     
    # 获取用药详细 (点击 停药 调整 时 调用当前的用药记录)

    public function getdetailById($id) {
        $data = $this->drugService->getdetailById($id);
        if (!$data) {
            return $this->error(42200, "数据异常，该用药不存在");
        } 
        $usageDosageOther = $data->usage_dosage_other ?? "";
        $data->usage_dosage_other = $this->serializeUsageDosageOther($usageDosageOther, 2);

        return $this->success($data);
    }
    
        /*
     * 用药列表
     */

    public function getDrugList(Request $request) {
        $data = $request->all();
        $validate = Validator::make($data, [
                    'user_id' => 'required', 
                    'mode' => 'required|in:1,2,3,4'
        ]);
        if ($validate->fails()) {
            return $this->error(42200, $validate->errors()->toJson());
        }

        $res = $this->drugService->getUserDrugList($data["user_id"], $data["mode"]);
        $ret = [];
        foreach ($res as $item) {
            #依赖时间点 
            $drugType = $item["drug_type"];
            switch ($drugType) {
                case 1:
                case 4:
                    $relationDate = $item["start_date"];
                    break;
                case 2:
                    $relationDate = $item["adjust_date"];
                    break;
                case 3:
                    $relationDate = $item["end_date"];
                    break;
            }
            $newDrugid = $item["pituitary_drugs_id"];
            //舍弃 
            $usageDosageOther = $item["usage_dosage_other"] ?? "";
            $item["usage_dosage_other"] = $this->serializeUsageDosageOther($usageDosageOther, 2);

            $ret[$newDrugid] = $item;
            $ret[$newDrugid]["id"] = $newDrugid;
                
        }


        $retRes = [
            "used" => [],
            "stop" => [],
            "all" => []
        ];
        foreach ($ret as $item) {
            if ($item["is_used"] == 1) {
                $retRes["used"][] = $item;
                $retRes["all"][] = $item;
            } else if ($item["is_used"] == 0) {
                $retRes["stop"][] = $item;
                $retRes["all"][] = $item;
            }
        }
        return $this->success($retRes);
    }

}
